package com.quanquan.parking.configBeans;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import utils.UUIDGenerator;

import java.util.Map;

/**
 * 功能描述: 发送rabbitMq
 *
 * @ClassName: RabbitSender
 * @Author: xiaoqianh丶
 * @Date: 2019-03-23 22:18
 * @Version: V1.0
 */
@Component
public class RabbitSender {

    private final RabbitTemplate rabbitTemplate;

    final RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, cause) -> {
        if (!ack) {
            //todo  没有发到队列上的消息进行记录存到数据库里或是写到日志管理里
        }
    };

    final RabbitTemplate.ReturnCallback returnCallback = (message, replyCode, replyText, exchange, routingKey) -> {
        System.err.println("return exchange :" + exchange + "routingKey :" + routingKey + "replyCode :" + replyCode + "replyText:" + replyText);
    };

    @Autowired
    public RabbitSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 发送消息到 rabbitMq
     * @param message
     * @param properties
     * @param exchange
     * @param routing
     */
    public void sendMessageToMQ(Object message, Map<String, Object> properties,String exchange,String routing) {
        MessageHeaders messageHeaders = new MessageHeaders(properties);
        Message<Object> msg = MessageBuilder.createMessage(message, messageHeaders);
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        //全局唯一 id
        String messageId = UUIDGenerator.getUUID();
        CorrelationData correlationData = new CorrelationData(messageId);

        rabbitTemplate.convertAndSend(exchange,routing,msg,correlationData);

    }


}
